namespace HZY.Framework.Repository.EntityFramework.Attributes;

/// <summary>
/// 逻辑删除，软删除
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class TableLogicAttribute : Attribute
{
    /// <summary>
    /// 非删除的值
    /// </summary>
    public object NonDeleteValue { get; set; }

    /// <summary>
    /// 删除的值
    /// </summary>
    public object DeleteValue { get; set; }

    /// <summary>
    /// 逻辑删除类型
    /// </summary>
    public TableLogicType TableLogicType { get; set; } = TableLogicType.Default;

    /// <summary>
    /// 逻辑删除，软删除
    /// </summary>
    public TableLogicAttribute()
    {
        NonDeleteValue = 0;
        DeleteValue = 1;
    }

    /// <summary>
    /// 逻辑删除，软删除
    /// </summary>
    /// <param name="nonDeleteValue"></param>
    /// <param name="deleteValue"></param>
    public TableLogicAttribute(object nonDeleteValue, object deleteValue)
    {
        NonDeleteValue = nonDeleteValue;
        DeleteValue = deleteValue;
    }

    /// <summary>
    /// 获取逻辑删除特性,的属性信息
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static PropertyInfo? GetTableLogicPropertyInfo(Type type)
    {
        return type.GetProperties().FirstOrDefault(x => x.GetCustomAttribute<TableLogicAttribute>() != null);
    }

    /// <summary>
    /// 获取逻辑删除特性
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static TableLogicAttribute? GetTableLogic(Type type)
    {
        var propertyInfos = type.GetProperties();

        foreach (var propertyInfo in propertyInfos)
        {
            if (propertyInfo.GetCustomAttribute<TableLogicAttribute>() != null)
            {
                return propertyInfo.GetCustomAttribute<TableLogicAttribute>();
            }
        }

        return null;
    }

    /// <summary>
    /// 是否有逻辑删除
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static bool HasTableLogic(Type type)
    {
        return type.GetProperties().Any(x => x.GetCustomAttribute<TableLogicAttribute>() != null);
    }

    /// <summary>
    /// 是否是逻辑删除字段
    /// </summary>
    /// <param name="propertyInfo"></param>
    /// <returns></returns>
    public static bool IsTableLogic(PropertyInfo propertyInfo)
    {
        return propertyInfo.GetCustomAttribute<TableLogicAttribute>() != null;
    }
}

public enum TableLogicType
{
    /// <summary>
    /// 默认，逻辑删除。满足 NonDeleteValue 和 DeleteValue 即可
    /// </summary>
    Default,

    /// <summary>
    /// Null 或 0 是非删除的值
    /// </summary>
    NullOr0NonDeleteValue,
}